﻿module Sustainalytics.Controversies {

    import Company = Sustainalytics.Company;
    import LRTM = Sustainalytics.LRTM;
    import ResearchState = Sustainalytics.Company.ResearchState;

    export class ControversiesController extends Research.ResearchPageController {

        // currently active view
        public viewName: string;
        public selectedControversyIndicator: ControversyIndicatorDto;
        public selectedEventIndicator: EventIndicatorDto;

        public hasControversyResearch: boolean = false;
        public isControversiesFeatureEnabled: boolean = false;

        public noResearchMessage: string;

        public currentUrl:string;

        public $routeParams: any;
        // whether current view is still loading
        public isInitLoading: boolean;

        private userId: string;
        private accountId: string;

        constructor(
            private $rootScope: ng.IScope,
            public $scope: Company.ICompanyBasedScope,
            public $q: ng.IQService,
            public $timeout: ng.ITimeoutService,
            public $location: ng.ILocationService,
            public RoutingService: Routing.IRoutingService,
            public CompanyService: Company.CompanyService,
            protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {

            super($scope, $q, $location, RoutingService, CompanyService);

            console.log('ControversiesController');

            var ctx = this;
            $scope['controversies'] = ctx;

            ctx.$routeParams = ctx.RoutingService.getRouteParams();

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.currentUrl = ctx.$location.url();

            ctx.init();
        }

        // init logic
        private init(): ng.IPromise<any> {
            var ctx = this;

            ctx.isInitLoading = true;

            var def = ctx.$q.defer();

            var initPromise = super.initPage();


            // set Summary view as the default view
            initPromise.then(
                // success
                () => {                    
                    this.hasControversyResearch = (this.company.controversyResearchState == ResearchState.ResearchAvailable);
                    
                    if (this.company.controversyResearchState == ResearchState.ResearchInProgress)
                        this.noResearchMessage = "Research in progress.";
                    else if (this.company.controversyResearchState == ResearchState.FrameworkNotApplicable)
                        this.noResearchMessage = "Framework not applicable.";
                    else if (this.company.controversyResearchState == ResearchState.ResearchNotAvailable)
                        this.noResearchMessage = "Research not available.";

                    var promise1 = this.getControversiesFeatureUniverse(this.company.id);

                    this.$q.all([promise1]).then(
                        // success
                        () => {

                            this.$timeout(() => {
                                this.$scope.$apply(() => {

                                    this.viewName = ControversiesViewNames.Summary;

                                    if (this.$rootScope['selectedControversyIndicator'] != null) {
                                        this.goToControversyIndicator(this.$rootScope['selectedControversyIndicator']);
                                        if (this.$rootScope['selectedEventIndicator'] != null) {
                                            this.goToEventIndicator(this.$rootScope['selectedControversyIndicator'], this.$rootScope['selectedEventIndicator']);
                                        }
                                    }
                                });
                            });

                            def.resolve();
                        },
                        // error
                        function (reason) {
                            def.reject(reason);
                        });
                },
                // error
                function (reason) {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Controversies: Controversies Controller -> Error initializing' });

                    def.reject(reason);
                });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;

                if (ctx.company != undefined) {
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.userId,
                        'cookieDomain': 'none',
                        'name': 'globalAccess'
                    });

                    ga('globalAccess.set', 'dimension1', ctx.userId);

                    var dateNow = new Date();
                    var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
                    var gaObject: any = {
                        Date: dateNowString,
                        AccountId: ctx.accountId,
                        UserId: ctx.userId,
                        CompanyId: ctx.company.id
                    };

                    ga('globalAccess.send', {
                        'hitType': 'event',
                        'eventCategory': 'Research',
                        'eventAction': 'OnscreenControversyReport',
                        'eventLabel': JSON.stringify(gaObject)
                    });
                }
            });

            return promise;
        }

        private getControversiesFeatureUniverse(companyId): ng.IPromise<Company.CorporateDataExtendedDto> {
            var ctx = this;
            var def = ctx.$q.defer();
            
            ctx.CompanyService.getById(companyId, Common.AccountFeature.Controversies).then(
                function (company) {
                    ctx.isControversiesFeatureEnabled = company.data.isEnabled;
                    def.resolve(company);
                },
                function (reason) {
                    def.reject(reason);
                });

            return def.promise;
        }

        // change currently active view
        public changeView(viewName: string): void {
            var ctx = this;

            ctx.$location.hash("");

            if (viewName) {
                ctx.viewName = viewName;
            }

            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Onscreen-Report', 'eventAction': 'Controversies - ESG Tabs', 'eventLabel': viewName
            });

        }

        public getViewNames(): ControversiesViewNames {
            return ControversiesViewNames;
        }

        public goToControversyIndicator(controversyIndicator: ControversyIndicatorDto = null) {
            var ctx = this;
            if (controversyIndicator) {

                this.selectedControversyIndicator = controversyIndicator;

                switch (controversyIndicator.themeName) {
                    case "Environment":
                        ctx.changeView(ControversiesViewNames.Environment);
                        break;
                    case "Social":
                        ctx.changeView(ControversiesViewNames.Social);
                        break;
                    case "Governance":
                        ctx.changeView(ControversiesViewNames.Governance);
                        break;
                    default:
                        ctx.changeView(ControversiesViewNames.Summary);
                }
            }
        }

        public goToEventIndicator(controversyIndicator: ControversyIndicatorDto = null, eventIndicator: EventIndicatorDto = null) {
            var ctx = this;
            if (controversyIndicator && eventIndicator) {

                ctx.selectedControversyIndicator = controversyIndicator;
                ctx.selectedEventIndicator = eventIndicator;

                switch (controversyIndicator.themeName) {
                    case "Environment":
                        ctx.changeView(ControversiesViewNames.Environment);
                        break;
                    case "Social":
                        ctx.changeView(ControversiesViewNames.Social);
                        break;
                    case "Governance":
                        ctx.changeView(ControversiesViewNames.Governance);
                        break;
                    default:
                        ctx.changeView(ControversiesViewNames.Summary);
                }
            }
        }
        
        public GetControversiesPdfDownloadEnabled(): boolean {
            var ctx = this;
            var result = true;

            if (!ctx.isControversiesFeatureEnabled || !ctx.hasControversyResearch) {
                result = false;
            }

            return result;
        }

        public addControversyReportToMostActiveReports() {
            var ctx = this;
            var now = new Date();

            var nameNoGuid = ctx.company.companyNameUrlFriendly.substring(0, ctx.company.companyNameUrlFriendly.length - 37);
            var reportName = nameNoGuid + "_ControversyReport_" + ('0' + now.getDate()).slice(-2) + ('0' + (1+now.getMonth())).slice(-2) + now.getFullYear();
            ctx.LongRunningTaskManagerService.runTask(reportName,
                JSON.stringify(ctx.company.id),
                LRTM.LongRunningTaskTypeEnum.ControversyReportPDF, true, null);
            
            ga('create', 'UA-4379897-6', {
                'userId': ctx.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.userId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: ctx.accountId,
                UserId: ctx.userId,
                CompanyId: ctx.company.id
            };

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Research', 'eventAction': 'PDFControversyReport', 'eventLabel': JSON.stringify(gaObject)
            });
        }
    }

    export var controversiesControllerName = 'ControversiesController';

    angular.module(controversiesModuleName).controller(controversiesControllerName,
        ['$rootScope', '$scope', '$q', '$timeout', '$location', 'RoutingService', 'CompanyService', 'LongRunningTaskManagerService', ControversiesController]);
} 